import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:memo/model/task.dart';
import 'package:memo/pages/detail_task.dart';
import 'package:memo/utils/toast.dart';
import 'package:memo/service/task_dao.dart';
import 'package:memo/utils/weather.dart';

import 'add_task.dart';
import 'search_task.dart';

class HomePage extends StatefulWidget {
  @override
  _HomePageState createState() => _HomePageState();
}

class _HomePageState extends State<HomePage>
    with SingleTickerProviderStateMixin {
  List<Task> tasks = [];
  TaskDao taskDao;

  final List<Tab> _tabs = <Tab>[
    Tab(text: "全部"),
    Tab(text: "未完成"),
    Tab(text: "已完成"),
  ];
  var _tabController;

  WeatherData weather = WeatherData.fromJson({
    "temperature": -9999.0,
    "windDirection": "",
    "windPower": 2,
    "humidity": 63.0,
    "updateTime": "",
    "weather": "",
    "visibility": "",
    "rainfall": 0.0,
    "pm25": 39.0
  });

  String region = "";

  @override
  void initState() {
    super.initState();
    taskDao = TaskDao();
    fetchWeather().then((value) {
      setState(() {
        weather = value.data.weatherData;
        region = value.data.region;
      });
    });

    _tabController = TabController(vsync: this, length: _tabs.length);
    _tabController.addListener(() {
      _changeList();
    });

    taskDao.tasks().then((value) {
      setState(() {
        tasks = value;
      });
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        centerTitle: true,
        title: Text("备忘录"),
        actions: <Widget>[
          IconButton(
            icon: Icon(
              Icons.add,
              size: 35,
            ),
            onPressed: () => _jumpToAddTaskPage(context),
          )
        ],
        bottom: TabBar(
          tabs: _tabs,
          controller: _tabController,
        ),
      ),
      body: ListView.separated(
        itemCount: tasks.length,
        itemBuilder: (BuildContext context, int index) {
          return ListTile(
            onTap: () => _jumpToDetailPage(context, index),
            title: _buildContent(index),
            subtitle: Text('截止时间:${tasks[index].endTimeStr}'),
            leading: _buildIsFinish(index),
            trailing: _buildDelete(index),
          );
        },
        separatorBuilder: (BuildContext context, int index) => Divider(
          color: Colors.grey[600],
        ),
      ),
      drawer: Drawer(
        child: ListView(
          padding: EdgeInsets.zero,
          children: <Widget>[
            DrawerHeader(
              child: RichText(
                  text: TextSpan(
                text:
                    "${region}\n${weather.windDirection}\n${weather.temperature > -9999.0 ? weather.temperature.toString() + '℃' : ''}\n${weather.weather}",
                style: TextStyle(fontSize: 14, color: Colors.black),
              )),
              decoration: BoxDecoration(
                color: Colors.blue,
              ),
            ),
            ListTile(
              title: Text('搜索'),
              leading: new CircleAvatar(
                child: new Icon(Icons.search),
              ),
              onTap: () => _jumpToSearchTaskPage(context),
            ),
          ],
        ),
      ),
    );
  }

  Widget _buildContent(index) {
    return Text(
      tasks[index].content,
      style: TextStyle(fontSize: 18),
      maxLines: 2,
      overflow: TextOverflow.ellipsis,
    );
  }

  Widget _buildIsFinish(index) {
    return GestureDetector(
      child: tasks[index].isFinish
          ? Icon(Icons.check_circle)
          : Icon(Icons.check_circle_outline),
      onTap: () {
        tasks[index].isFinish = !tasks[index].isFinish;
        taskDao.updateTask(tasks[index]);
        if (_tabController.index != 0) {
          tasks.removeAt(index);
        }
        setState(() {});
      },
    );
  }

  Widget _buildDelete(index) {
    return IconButton(
      icon: Icon(Icons.delete),
      onPressed: () {
        taskDao.deleteTask(tasks[index].id);
        setState(() {
          tasks.removeAt(index);
        });
        Toast.toast(context, msg: "删除成功！", position: ToastPostion.top);
      },
    );
  }

  void _changeList() {
    switch (_tabController.index) {
      case 0:
        taskDao.tasks().then((value) {
          setState(() {
            tasks = value;
          });
        });
        break;
      case 1:
        taskDao.tasksWhere(0).then((value) {
          setState(() {
            tasks = value;
          });
        });
        break;
      case 2:
        taskDao.tasksWhere(1).then((value) {
          setState(() {
            tasks = value;
          });
        });
        break;
    }
  }

  void _jumpToAddTaskPage(context) {
    Navigator.of(context)
        .push(MaterialPageRoute(builder: (ctx) => AddTaskPage()))
        .then((value) {
      _changeList();
    });
  }

  void _jumpToSearchTaskPage(context) {
    Navigator.of(context)
        .push(MaterialPageRoute(builder: (ctx) => SearchTaskPage()))
        .then((value) {
      _changeList();
    });
  }

  void _jumpToDetailPage(context, index) {
    Navigator.of(context)
        .push(MaterialPageRoute(
            builder: (ctx) => DetailPage(taskDao, tasks[index])))
        .then((res) {
      _changeList();
    });
  }
}
